import React from 'react';
import { Row, Col, Input, Button, Tree, Divider,message} from 'antd';
import {injectIntl} from 'react-intl';
import axios from 'axios';

const TreeNode = Tree.TreeNode;

class AddRole extends React.Component {
    constructor(props) {
        super(props);
        if (!this.props.location.state) {
            this.props.history.replace('/company/newRoleManager');
        }
        this.info=this.props.location.state?this.props.location.state.info:undefined;
        this.state = {
            name: this.info?this.info.name:'',
            relCheckedKeys: [],
            treeData: [],
            expandedKeys: [],
            autoExpandParent: true,
            checkedKeys: [],
            selectedKeys: [],
        };

    }

    componentDidMount() {
        this.fromAdd();
    }
    fromAdd=()=>{
        axios.get('/api/author/qry', {params: {type: 2,roleId:this.info?this.info.id:undefined}}).then((res) => {
            if (res && res.data) {
                //组装parent对应的id
                let level1 = res.data.filter((item) => (item.children = [],
                    item.title = item.name,
                    item.key = item.id,
                item.level === "1"));
                let level2 = res.data.filter((item) => (
                    item.title = item.name,
                        item.key = item.id,
                    item.level === "2"));
                level2.map((item) => {
                    level1.map((k) => {
                        if (item.parent === k.id) {
                            k.children.push(item)
                        }
                    })
                });
                console.log(`level1`,level1)
                this.setState({
                    treeData: level1
                },()=>{this.hasAuthor(this.state.treeData)});
            }
        })
    };

    change = (e) => {
        let name = e.target.value;
        this.setState({
            name
        })
    };

    hasAuthor=(treeData)=>{
        let expandedKeys=[];
        let checkedKeys=[];
        treeData.map((item)=>{
            if(item.isChosen==="1"){
                expandedKeys.push(item.id);
                item.children.map((k)=>{
                    if(k.isChosen==="1"){
                        checkedKeys.push(k.id);
                    }
                })
            }
        });
        /*https://ant.design/components/tree-cn/*/
        this.setState({
            expandedKeys:expandedKeys,
            checkedKeys:checkedKeys
        });
    };

    //提交表格验证
    handleSubmit = (e) => {
        e.preventDefault();
        const common = this.props.intl.messages.common;

        // 空值验证
        if(!this.state.name){
            message.error(common.roleNotEmpty);
            return
        }
        if(this.props.location.state.status === "add"){
            axios.get(`/api/role/add`,{params:{name:this.state.name,author:this.state.relCheckedKeys.join(',')}}).then(res=>{
                message.success(common.OperateSuccessfully);
                this.props.history.goBack()
            })
        }
        if(this.props.location.state.status === "modify"){
            console.log(this.state.relCheckedKeys,[...this.state.expandedKeys,...this.state.checkedKeys]);
            let author=this.state.relCheckedKeys.length>0?this.state.relCheckedKeys.join(','):[...this.state.expandedKeys,...this.state.checkedKeys].join(',');
            axios.get(`/api/role/mod`,{params:{name:this.state.name,author:author,id:this.props.location.state.info.id}}).then(res=>{
                message.success(common.modifySuccessfully);
                this.props.history.goBack()
            })
        }
    };

    onExpand = (expandedKeys) => {
        console.log('onExpand', arguments);
        // if not set autoExpandParent to false, if children expanded, parent can not collapse.
        // or, you can remove all expanded children keys.
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    };
    onCheck = (checkedKeys, info) => {
        console.log([...checkedKeys, ...info.halfCheckedKeys]);
        this.setState({checkedKeys:checkedKeys,relCheckedKeys:[...checkedKeys, ...info.halfCheckedKeys]});
    };
    renderTreeNodes = (data) => {
        return data.map((item) => {
            if (item.children) {
                return (
                    <TreeNode title={item.title} key={item.key} dataRef={item}>
                        {this.renderTreeNodes(item.children)}
                    </TreeNode>
                );
            }
            return <TreeNode {...item} />;
        });
    };

    render() {
        const common = this.props.intl.messages.common;
        return (
            <Row>
                <Col span={24}>
                    <Row gutter={12}>
                        <Col>
                            <Input placeholder={common.roleName} style={{width: 350}} onChange={this.change} defaultValue={this.state.name}/>
                        </Col>
                    </Row>
                </Col>
                <Col span={24}>
                    <Tree
                        checkable
                        onExpand={this.onExpand}
                        expandedKeys={this.state.expandedKeys}
                        autoExpandParent={this.state.autoExpandParent}
                        onCheck={this.onCheck}
                        checkedKeys={this.state.checkedKeys}
                    >
                        {this.renderTreeNodes(this.state.treeData)}
                    </Tree>
                </Col>
                <Divider/>
                <Col span={24}>
                        <Button className="ant-btn-84" type="primary" style={{marginRight: 8}}
                                onClick={this.handleSubmit}>{common.save}</Button>
                </Col>
            </Row>
        )
    }
}


export default injectIntl(AddRole);